package com.hxzy.tms.aciton;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;

import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.util.WebUtils;

import com.google.gson.Gson;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public abstract class AbstractAction extends ActionSupport {
    protected Logger logger = LoggerFactory.getLogger(getClass());

    private static final long serialVersionUID = 2900126534347830365L;

    private String redirectUrl;

    private Map<String, Object> stack = new HashMap<String, Object>();

    protected boolean isGET() {
        return "GET".equals(ServletActionContext.getRequest().getMethod());
    }

    protected boolean isPOST() {
        return "POST".equals(ServletActionContext.getRequest().getMethod());
    }

    protected String ipv4() {
        return ServletActionContext.getRequest().getRemoteAddr();
    }
    
    protected String _404() {
        addActionError("您要找的资源不存在");
        return ERROR;
    }

    protected void writeJson(Object data) {
        ServletActionContext.getResponse().setCharacterEncoding("utf-8");
        ServletActionContext.getResponse().setContentType("application/json");

        try {
            Gson gson = new Gson();
            ServletActionContext.getResponse().getWriter().println(gson.toJson(data));
        } catch (IOException e) {
            logger.error("向客户端写入 json 字符串", e);
        }
    }

    protected void assign(String key, Object value) {
        stack.put(key, value);
        ActionContext.getContext().getValueStack().push(stack);
    }

    protected void addCookie(Cookie cookie) {
        ServletActionContext.getResponse().addCookie(cookie);
    }

    protected String getCookie(String key) {
        Cookie c = WebUtils.getCookie(ServletActionContext.getRequest(), key);
        return c != null ? c.getValue() : null;
    }

    public String getRedirectUrl() {
        return redirectUrl;
    }

    public void setRedirectUrl(String redirectUrl) {
        this.redirectUrl = redirectUrl;
    }

    public String getParameter(String key) {
        return ServletActionContext.getRequest().getParameter(key);
    }

    protected final class ActionResult<T> {

        public final int status;
        public final T data;
        public final String message;

        public ActionResult(int status) {
            this.status = status;
            this.data = null;
            this.message = "";
        }

        public ActionResult(int status, T data) {
            this.status = status;
            this.data = data;
            this.message = "";
        }

        public ActionResult(int status, T data, String message) {
            this.status = status;
            this.data = data;
            this.message = message;
        }

    }

}
